import { useRefNow } from "@/hooks/useRefNow";
import { LoadingOutlined, SearchOutlined } from "@ant-design/icons";
import { Button, Input, InputProps, InputRef } from "antd";
import { Ref, useCallback } from "react";

export interface IInputSearchProps extends InputProps {
  _ref?: Ref<InputRef> | undefined;
  loading?: boolean;
  onSearch?(): void;
}
export function InputSearch(props: IInputSearchProps) {
  const {
    _ref, loading, disabled, onSearch, onPressEnter, onBlur,
    prefix = '搜索', variant = 'underlined', size = 'small', ..._p
  } = props
  const _disabled = loading || disabled;
  const _ref_onPressEnter = useRefNow(onPressEnter)
  const _ref_onBlur = useRefNow(onBlur)
  const _ref_onSearch = useRefNow(onSearch)

  const _onPressEnter = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
    _ref_onPressEnter.current?.(e);
    _ref_onSearch.current?.();
  }, []);

  const _onBlur = useCallback((e: React.FocusEvent<HTMLInputElement, Element>) => {
    _ref_onBlur.current?.(e);
    _ref_onSearch.current?.();
  }, []);

  const _onClickSearch = useCallback((e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    _ref_onSearch.current?.();
    e.preventDefault();
  }, [])

  return (
    <Input
      {..._p}
      ref={_ref}
      disabled={_disabled}
      onPressEnter={_onPressEnter}
      onBlur={_onBlur}
      prefix={prefix}
      variant={variant}
      size={size}
      suffix={
        <Button
          type="text"
          size={size}
          disabled={_disabled}
          onClick={_onClickSearch}>
          {loading ? <LoadingOutlined /> : <SearchOutlined />}
        </Button>
      } />
  )
}